package com.kylin.common.core.config;

import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.kylin.common.core.config.support.KylinFastJsonHttpMessageConverter;
import com.kylin.common.core.filter.ApiLogHandler;
import com.kylin.common.core.filter.DefaultApiLoginHandler;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import static org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type.SERVLET;

/**
 * WebMvc配置
 *
 * @author wuhao
 * @version 1.0 - 2019/6/24
 */
@AutoConfiguration
@ConditionalOnWebApplication(type = SERVLET)
@ConditionalOnProperty(prefix = "kylin.core.converter.fastjson", name = "enable", havingValue = "true", matchIfMissing = true)
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("*")
                .allowedHeaders("*");
    }

    @Bean
    KylinFastJsonHttpMessageConverter fastJsonHttpMessageConverter(){

        KylinFastJsonHttpMessageConverter fastJsonHttpMessageConverter =new KylinFastJsonHttpMessageConverter();

        FastJsonConfig config= new FastJsonConfig();

        // mmodify by wuhao at 20210508 为了解决前端精度丢失问题
//        config.setSerializeFilters((ValueFilter) (object, name, value) -> {
//            if ((StringUtils.endsWith(name, "Id") || StringUtils.equals(name,"id")) && value != null
////                if (StringUtils.equals(name,"id") && value != null
//                    && value.getClass() == Long.class ) {
//                return String.valueOf(value);
//            }
//            return value;
//        });

        //日期格式
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");
        //数据编码
        config.setCharset(StandardCharsets.UTF_8);
        config.setWriterFeatures(
                ///SerializerFeature.WriteClassName,//是否在生成的json中输出类名
                //SerializerFeature.WriteMapNullValue,//是否输出value为null的字符串
                //生成的json格式化
                JSONWriter.Feature.PrettyFormat,
//                JSONWriter.Feature.WriteNullListAsEmpty,//空集合输出[]而非null
                //空字符串输出“”而不是null
                JSONWriter.Feature.WriteNullStringAsEmpty
        );

        //配置完之后还需要在config里面响应一下编码
        fastJsonHttpMessageConverter.setFastJsonConfig(config);

        //创建fastJson消息转换器
        List<MediaType> supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON);
        fastJsonHttpMessageConverter.setSupportedMediaTypes(supportedMediaTypes);

        return fastJsonHttpMessageConverter;
    }



//    @Bean
//    public FilterRegistrationBean<ApiLogFilter> myFilterRegistration() {
//        FilterRegistrationBean<ApiLogFilter> registration = new FilterRegistrationBean<>();
//        registration.setFilter(new ApiLogFilter());
//        registration.addUrlPatterns("/*");
//        registration.setName("accessLog");
//        registration.setOrder(Ordered.HIGHEST_PRECEDENCE); // 设置Filter的执行顺序，此处设置为最高优先级
//        return registration;
//    }


    /**
     * 默认接口日志处理类
     * @return
     * @author wuhao
     * @since 2.2.3 - 2021/12/11
     */
    @Bean
    @ConditionalOnMissingBean
    public ApiLogHandler apiLogHandler()
    {
        return new DefaultApiLoginHandler();
    }


//    @Bean
//    public TenantInterceptor tenantInterceptor() {
//        return new TenantInterceptor();
//    }
//
//    @Override
//    public void addInterceptors(InterceptorRegistry registry) {
//        registry.addInterceptor(tenantInterceptor()).addPathPatterns("/**").order(0);
//        // 这里的order(0)指示了将这个拦截器放在最前面，以确保它首先执行
//    }

}